const uploadModel = require('../models/upload');
const AElfModule = require('../models/aelf')
const PkManageModule = require('../models/private_key_manage')
const HistoryModule = require('../models/history')

exports.form = (req, res) => {
    res.render('cr_upload', { title: '版权上链' });
};

exports.upload = (req, res) => {
    /**设置响应头允许ajax跨域访问**/
    res.setHeader("Access-Control-Allow-Origin", "*");
    uploadModel.uploadPhoto(req, 'public/images', function (err, fields, uploadPath) {
        if (err) {
            return res.json({
                errCode: 1,
                errMsg: '上传图片错误'
            });
        }
        res.json({
            errCode: 0,
            errMsg: '上传成功',
            fields: fields,
        });
        console.log(fields);    //表单中字段信息
        console.log(uploadPath);    //上传图片的相对路径

        var aelf = new AElfModule();
        var log = new HistoryModule(fields.owner);
        PkManageModule.get_priKey_by_user(fields.owner, (user) => {
            aelf.check_chain_state((state) => {
                if (state) {
                    console.log(user)
                    aelf.load_wallet(user.priKey, (wallet) => {
                        if (typeof (wallet) !== 'undefined') {
                            aelf.load_contract(false, (param) => {
                                console.log("contract prepared");
                                aelf.approve(param, 10000, (res) =>{
                                    aelf.load_contract(true, (param) => {
                                        console.log("contract prepared");
                                        aelf.CR_Upload(param, fields.creator, fields.id, (ret)=>{
                                            log.Log(ret['TransactionId'])
                                        });
                                    });
                                });
                            });
                        }
                    });
                }
            })
        });
    });
}